package com.oujiong.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.oujiong.redisson.RedissonLock;

import lombok.extern.slf4j.Slf4j;

/**
 * 不基于注解方式锁操作
 */
@RestController
@Slf4j
public class LockController {

	@Autowired
	RedissonLock redissonLock;

	/**
	 * 模拟这个是商品库存
	 */
	public static volatile Integer TOTAL = 10;

	/**
	 * http://localhost:8086/lock-decrease-stock
	 */
	@GetMapping("lock-decrease-stock")
	public String lockDecreaseStock() throws InterruptedException {
		redissonLock.lock("lock", 10L);
		if (LockController.TOTAL > 0) {
			LockController.TOTAL--;
		}
		Thread.sleep(50);
		LockController.log.info("===lock===减完库存后,当前库存===" + LockController.TOTAL);
		//如果该线程还持有该锁，那么释放该锁。如果该线程不持有该锁，说明该线程的锁已到过期时间，自动释放锁
		if (redissonLock.isHeldByCurrentThread("lock")) {
			redissonLock.unlock("lock");
		}
		return "=================================";
	}

	/**
	 * http://localhost:8086/trylock-decrease-stock
	 */
	@GetMapping("trylock-decrease-stock")
	public String trylockDecreaseStock() throws InterruptedException {
		if (redissonLock.tryLock("trylock", 5L, 200L)) {
			if (LockController.TOTAL > 0) {
				LockController.TOTAL--;
			}
			Thread.sleep(50);
			redissonLock.unlock("trylock");
			LockController.log.info("====tryLock===减完库存后,当前库存===" + LockController.TOTAL);
		} else {
			LockController.log.info("[ExecutorRedisson]获取锁失败");
		}
		return "===================================";
	}

}
